import multer from "@koa/multer";
import fs from "fs";
import fse from "fs-extra";
import { Paths } from "./paths";
import { nanoid } from "nanoid";

//上传文件存放路径、及文件命名
const storage = multer.diskStorage({
  destination: function (_: any, __: any, cb: any) {
    const upload = Paths.resources("upload");
    if (!fs.existsSync(upload)) fse.mkdirsSync(upload);
    cb(null, Paths.resources("upload"));
  },
  filename: function (_: any, file: any, cb: any) {
    file.originalname = Buffer.from(file.originalname, "latin1").toString("utf-8");
    let type = file.originalname.split(".")[1];
    cb(null, `${Date.now().toString(16)}-${nanoid(8)}.${type}`);
  }
});

const limits = {
  fileSize: 50 * 1024 * 1024 * 1024 //文件大小 单位 b
};

export const upload = multer({ storage, limits });
